# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase


class Solution(SolutionBase):
    # 解题的方法，命名和Leetcode的保持一致即可
    def snakesAndLadders(self, board: List[List[int]]) -> int:
        # 得到下一步可能走到的格子
        # 判断是否超过总格子
        # 判断是否需要跳跃
        def get_next_step(curr_cell, total_count) -> List[int]:
            new_steps = []
            for i in range(1, 7):
                next_cell = curr_cell + i
                if next_cell == total_count:
                    new_steps.clear()
                    new_steps.append(next_cell)
                    break

                if next_cell < total_count:
                    row_id, col_id = get_row_col(next_cell, row_count, col_count)
                    nonlocal board
                    if board[row_id][col_id] == -1:
                        new_steps.append(next_cell)
                    else:
                        new_steps.append(board[row_id][col_id])

            return new_steps

        def get_row_col(cell_no, total_row, total_col):
            value1 = ((cell_no - 1) // total_row)
            row_id = total_row - 1 - value1
            if value1 % 2 == 0:
                col_id = (cell_no - 1) % total_row
            else:
                col_id = total_col - 1 - (cell_no - 1) % total_row

            return row_id, col_id

        state_queue = [[1, 0]]  # 初始化状态，格子：0，Step：0
        visited_set = set()
        row_count = len(board)
        col_count = len(board[0])
        cell_number = row_count * col_count
        min_step = -1
        while len(state_queue) > 0:
            [cell_id, step_count] = state_queue.pop()
            next_steps = get_next_step(cell_id, cell_number)
            for cell in next_steps:
                if cell in visited_set:
                    continue

                row, col = get_row_col(cell, row_count, col_count)
                if cell == cell_number:
                    min_step = step_count + 1
                    return min_step

                visited_set.add(cell)
                state_queue.insert(0, [cell, step_count + 1])

        return min_step


if __name__ == '__main__':
    solution = Solution()

    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        (
            [[-1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, -1],
             [-1, 35, -1, -1, 13, -1],
             [-1, -1, -1, -1, -1, -1],
             [-1, 15, -1, -1, -1, -1]], 4)
    ]

    for case_item in testcases:
        # 获取测试用的case和期待的执行结果
        input1 = case_item[0]
        expect = case_item[len(case_item) - 1]
        exec_result = solution.snakesAndLadders(input1)

        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)

